﻿using System;
using System.Web.Mvc;
using CoreLibrary;
using CoreLibrary.JsonNet;
using CoreLibrary.Mvc;
using NLog;

namespace Web.Models.Common {

    public class JsonNetModelBinder<T> : DefaultModelBinder {

        public override object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {

            if (controllerContext.HttpContext == null) {
                throw new NullReferenceException("HttpContext is not intialized.");
            }

            var request = controllerContext.HttpContext.Request;
            if (request == null) {
                throw new NullReferenceException("HttpRequest is not intialized.");
            }


            if (request.IsAjaxRequest() || ( string.IsNullOrEmpty(request.ContentType)
            && !request.ContentType.ToLower().Contains(MimeTypes.Json) )) {
                return default(T);
            }

            if (request.InputStream.CanSeek) {
                request.InputStream.Position = 0;
            }

            try {
                var payload = IOUtil.ReadStringAndClose(request.InputStream);
                return JSON.Deserialize<T>(payload);
            } 
            catch (Exception exception) {
                LogManager.GetCurrentClassLogger().ErrorException(exception.Message, exception);
                return new Exception("The request is out of date, Please try again later.");
            }

        }
    }
}